﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Daniel Vaughan. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2012-02-18 13:47:14Z</CreationDate>
</File>
*/
#endregion

#if SL5
// Based on code from http://slouge.wordpress.com/2011/04/20/silverlight-x-static-markupextension-like-wpf/
using System;
using System.Reflection;
using System.Windows.Markup;
using System.Xaml;

namespace DanielVaughan.Windows.MarkupExtensions
{
	/// <summary>
	///  A markup extension to retrieve the values ​​of fields or properties.
	/// </summary>
	public class Static : IMarkupExtension<Object>
	{
		String member;
		Type type;

		/// <summary>
		/// Gets or sets the static member, for example, local: MyEnum.MyEnumValue if not otherwise Type MyEnumValue
		/// </summary>
		public string Member
		{
			get
			{
				return member;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException();
				}

				member = value;
			}
		}

		/// <summary>
		/// Gets or sets the type of the member to resolve.
		/// </summary>
		public Type Type
		{
			get
			{
				return type;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException();
				}

				type = value;
			}
		}

		/// <summary>
		///  Gets an object provides the type parameter. Retrieves a field or property.
		/// </summary>
		/// <param name="serviceProvider">Service to retrieve the service used for MarkupExtension.</param>
		/// <returns>
		///  An object corresponding to the string provided in paramettre (Member).
		/// </returns>
		public Object ProvideValue(IServiceProvider serviceProvider)
		{
			object result = null;
			bool typeResolveFailed = true;
			Type resolvedType = type;
			string fieldMemberName = null;
			string fullFieldMemberName = null;

			if (Member == null)
			{
				throw new InvalidOperationException("Member can't be null.");
			}

			if (Type != null) /* It was the type and member. */
			{
				fieldMemberName = Member;
				fullFieldMemberName = string.Format("{0}.{1}", resolvedType.FullName, Member);
			}
			else
			{
				/* It was not the type. We look if the string is formatted correctly 
			     * eg local: MyEnum.MyEnumeValue and try to resolve the type.*/
				Int32 index = Member.IndexOf('.');

				if (index >= 0)
				{
					string typeName = Member.Substring(0, index);

					if (!String.IsNullOrEmpty(typeName))
					{
						var xamlTypeResolver = (IXamlTypeResolver)serviceProvider.GetService(typeof(IXamlTypeResolver));

						if (xamlTypeResolver != null)
						{
							resolvedType = xamlTypeResolver.Resolve(typeName);
							fieldMemberName = Member.Substring(index + 1); // Member.Length - index - 1
							typeResolveFailed = String.IsNullOrEmpty(fieldMemberName);
						}
					}
				}
			}

			if (typeResolveFailed)
			{
				throw new InvalidOperationException("Member");
			}

			if (resolvedType.IsEnum) // if an enum so we try to solve the Member
			{
				result = Enum.Parse(resolvedType, fieldMemberName, true);
			}
			else //this is not an enum: probably a field or property
			{
				bool fail = true;

				FieldInfo field = resolvedType.GetField(fieldMemberName,
												BindingFlags.Public
												| BindingFlags.FlattenHierarchy
												| BindingFlags.Static);
				if (field != null)
				{
					fail = false;
					result = field.GetValue(null);
				}
				else //this is not a field, if you look at a property
				{
					//if you look at a property
					PropertyInfo property = resolvedType.GetProperty(fieldMemberName,
															 BindingFlags.Public
															 | BindingFlags.FlattenHierarchy
															 | BindingFlags.Static);

					if (property != null) //it is a property
					{
						fail = false;
						result = property.GetValue(null, null);
					}
				}

				if (fail)
				{
					throw new ArgumentException(fullFieldMemberName);
				}
			}

			return result;
		}
	}
}
#endif